﻿using MVVMtutorialAdvanced.Web;
using Riba.MVVMSL;

namespace MVVMtutorialAdvanced
{
	public class AuthorDetails_VM : ViewModelBase
	{
		public RelayCommand CommandOk { get; private set; }
		public RelayCommand CommandCancel { get; private set; }

		private Author _currentEntity;
		public Author CurrentEntity
		{
			get { return _currentEntity; }
			set { SetPropertyValue(ref _currentEntity, value, () => CurrentEntity); }
		}

		public AuthorDetails_VM()
		{
			CommandOk = new RelayCommand(OnCommandOk);
			CommandCancel = new RelayCommand(OnCommandCancel);

			if (IsInDesignTool)
				CurrentEntity = new Author { Id = 1, FirstName = "First", LastName = "Last" };

			ExchangeDataAvailable += vm_ExchangeDataAvailable;
		}

		private void vm_ExchangeDataAvailable(object sender, ExchangeDataAvailableEventArgs e)
		{
			CurrentEntity = ExchangeData as Author;

			CommandOk.IsEnabled = true;
			CommandCancel.IsEnabled = true;
		}

		private void OnCommandOk(object handler)
		{
			if (CurrentEntity.HasValidationErrors)
				return;
			if (CurrentEntity.FirstName == null || CurrentEntity.LastName == null)
				return;

			if (Callback != null)
				Callback(this, true);

			RaiseCloseChildWindowView();
		}

		private void OnCommandCancel(object handler)
		{
			if (Callback != null)
				Callback(this, false);

			RaiseCloseChildWindowView();
		}
	}
}
